package top.waikin.mooc.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.waikin.mooc.admin.domain.RoleDto;
import top.waikin.mooc.admin.service.AdminCacheService;
import top.waikin.mooc.admin.service.RolePermissionRelationService;
import top.waikin.mooc.admin.service.RoleService;
import top.waikin.mooc.entity.Role;
import top.waikin.mooc.entity.RolePermissionRelation;
import top.waikin.mooc.mapper.RoleMapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 后台用户角色 服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    RolePermissionRelationService rolePermissionRelationService;

    @Autowired
    AdminCacheService adminCacheService;

    @Override
    public int create(RoleDto roleDto) {
        Role role = new Role();
        BeanUtil.copyProperties(roleDto, role);
        save(role);
        return role.getId();
    }

    @Override
    public boolean update(int id, RoleDto roleDto) {
        Role role = new Role();
        BeanUtil.copyProperties(roleDto, role);
        role.setId(id);
        return updateById(role);
    }

    @Override
    public void increaseAdminCount(List<Integer> ids) {
        LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<Role>()
                .in(Role::getId, ids).setSql("admin_count = admin_count + 1");
        update(wrapper);
    }

    @Override
    public void decreaseAdminCount(List<Integer> ids) {
        LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<Role>()
                .in(Role::getId, ids).setSql("admin_count = admin_count - 1");
        update(wrapper);
    }

    @Override
    public boolean updatePermission(Integer id, List<Integer> permissionIds) {
        boolean b = true;
        // 删除原有关系
        Wrapper<RolePermissionRelation> wrapper = new LambdaQueryWrapper<RolePermissionRelation>()
                .eq(RolePermissionRelation::getRoleId, id);
        rolePermissionRelationService.remove(wrapper);
        // 建立新的关系
        if (CollectionUtil.isNotEmpty(permissionIds)) {
            List<RolePermissionRelation> rolePermissionRelations = permissionIds.stream()
                    .map(integer -> new RolePermissionRelation().setRoleId(id).setPermissionId(integer))
                    .collect(Collectors.toList());
            b = rolePermissionRelationService.saveBatch(rolePermissionRelations);
        }
        // 删除缓存
        adminCacheService.deletePermissionListByRole(id);

        return b;
    }
}
